package com.biz.service.auth.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import com.biz.dao.user.UserDAO;
import com.biz.dto.user.FunctionDTO;
import com.biz.dto.user.RoleDTO;
import com.framework.utils.LogicUtils;

public class SecurityMetadataSourceImpl implements FilterInvocationSecurityMetadataSource {

	private static Map<String, Collection<ConfigAttribute>> resourceMap;
	@Resource(name = "userDAOImpl")
	private UserDAO userDAO;

	public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
		String requestUrl = ((FilterInvocation) object).getRequestUrl();
		if (resourceMap == null) {
			loadResourceDefine();
		}
		Collection<ConfigAttribute> collection = resourceMap.get(requestUrl);
		if (collection == null) {
			collection = new ArrayList<ConfigAttribute>();
		}
		return collection;
	}

	public boolean supports(Class<?> clazz) {
		return true;
	}

	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}
	
	private void loadResourceDefine() {
		resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
		Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
		List<RoleDTO> roleList = userDAO.queryAllRole();
		if (LogicUtils.isNotNull(roleList)) {
			for (RoleDTO role : roleList) {

				List<FunctionDTO> funcList = role.getFunction();
				if (LogicUtils.isNotNull(funcList)) {
					for (FunctionDTO func : funcList) {
						atts.add(new SecurityConfig(String.valueOf(role.getRoleId())));
						Collection<ConfigAttribute> collection = resourceMap.get(func.getFuncUrl());
						if (collection == null) {
							resourceMap.put(func.getFuncUrl(), atts);
						} else {
							resourceMap.get(func.getFuncUrl())
									.add(new SecurityConfig(String.valueOf(role.getRoleId())));
						}
					}
				}
			}
		}

	}

}